package org.acghub.config.type;

import org.acghub.config.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @Desc
 * @Author miyuki4j
 * @Date 2025/7/24/星期四 14:17
 * @Version 1.0
 */
public class List2Type extends Type.CollectionType<List<List<?>>> {

    @Override
    public String name() {
        return "list2";
    }

    @Override
    public void parse(TableField field, String type, String delimiters) throws TypeParseException {
        int len = name().length();
        String token = type.substring(len + 1);
        token = token.substring(0, token.length() - 1);
        if (org.apache.commons.lang3.StringUtils.length(delimiters) < 2) {
            throw new TypeParseException("bad delimiters \"" + delimiters + "\"");
        }
        valueType = TypeFactory.getSimpleType(token);
        if (valueType == null) {
            throw new TypeParseException("invalid value type: " + token);
        }
        valueType.parse(field, token, delimiters.substring(2));
    }

    @Override
    public String javaInterface() {
        return "java.util.List<>";
    }

    @Override
    public String javaImplementation() {
        return "java.util.ArrayList";
    }

    @Override
    public String javaDeclaration() {
        return String.format("java.util.List<java.util.List<%s>>", valueType.javaDeclaration());
    }

    @Override
    protected List<List<?>> newCollection() {
        return new ArrayList<>();
    }

    @Override
    public List<List<?>> instance(String value, String delimiters) throws TypeInstanceException {
        try {
            List<List<?>> lists = new ArrayList<>();
            String firstDelimiter = StringUtils.getRegex(String.valueOf(delimiters.charAt(0)));
            String secondDelimiter = StringUtils.getRegex(String.valueOf(delimiters.charAt(1)));
            String remainDelimiter = delimiters.substring(2);
            String[] listStrArr = value.split(firstDelimiter);
            for (String listStr : listStrArr) {
                List<?> list = new ArrayList<>();
                String[] valStrArr = listStr.split(secondDelimiter);
                for (String valStr : valStrArr) {
                    list.add(valueType.instance(valStr, remainDelimiter));
                }
                lists.add(list);
            }
            return lists;
        } catch (Exception e) {
            throw new TypeInstanceException("parse map value:" + value, e);
        }
    }
}
